//
//  ST_DTChatTextCell.swift
//  DrinkTogether
//
//  Created by DouLei on 2018/6/25.
//  Copyright © 2018 DouLei. All rights reserved.
//

import UIKit
import SwifterSwift
import SwiftyJSON
import SDWebImage
import PINRemoteImage
//import Rswift

class ST_DTChatTextCell: ST_DTChatCell {
    
    
    fileprivate lazy var nobleIconImageView:UIImageView = {
        let v = UIImageView()
        v.contentMode = .scaleAspectFill
        v.clipsToBounds = true
        v.alpha = 0
//        v.backgroundColor = .random
        return v
    }()
    
    fileprivate lazy var gradientBackView:ST_FWGradientView = {
        let control = ST_FWGradientView()
        control.cornerRadius = 20
        control.borderColor = .clear
        control.borderWidth = 2
        control.bgLayer.locations = [0, 1]
        control.bgLayer.startPoint = CGPoint(x: 0, y: 0)
        control.bgLayer.endPoint = CGPoint(x: 0, y: 1)
        return control
    }()
    
    fileprivate lazy var goddessBubbleBackView:UIImageView = {
        let v = UIImageView()
        v.alpha = 0
//        v.contentMode = .scaleAspectFill
//        v.clipsToBounds = true
        //v.cornerRadius = 5
        return v
    }()
    
    fileprivate lazy var chatTextLabel:UILabel = {
        
        let control = UILabel()
        control.numberOfLines = 0
        control.font = DTChatTextFont
        control.textAlignment = .left
        
//        control.backgroundColor = Color.random
        
        return control
        
    }()
    
    
    
    override func commonInit(){
    
        super.commonInit()
        
        contentView.addSubview(gradientBackView)
        contentView.addSubview(goddessBubbleBackView)
        contentView.addSubview(chatTextLabel)
        contentView.addSubview(upload_error_btn)
        contentView.addSubview(nobleIconImageView)
        
    }
    
    private let leftTextColor = Color.init(hex: 0x8290A5)!
    
    private let rightTextColor = Color.white
    
    private lazy var goddessTextColor = UIColor(hex:0xEE359D)!
    
    private var lastBubble:BubbleEffectEnum?
    
//    private var lastNoble:NobleEffectEnum?
    
    override var message: ST_DTChatMessage!{
        didSet{
            
            if uuid != message.uuid{
                
                icon.sd_setImage(with: message.portraitUri.compress_image().url,for: UIControl.State.normal, completed: nil)
                
                chatTextLabel.text = message.chatText
                
                //gradientBackView.image = message.textBackImage
                
                self.uuid = message.uuid
                
//
//                icon.frame = message.iconFrame
//                chatTextLabel.frame = message.textFrame
//                textBackImageView.frame = message.textBackFrame
                
                gradientBackView.snp.updateConstraints { (make) in
                    make.width.equalTo(message.textBackFrame.width)
                    make.height.equalTo(message.textBackFrame.height)
                }
            }
            
            refresh_text_bubble_effect()
        }
        
    }
    
    /// 文字气泡刷新
    func refresh_text_bubble_effect() {
        
        guard let myId = ST_BTUserInfoManager.shared.current_account_info?.accid,message != nil else {
            return
        }
        
        
        let accid = message.direction == .receive ? message.chatID : myId
        
        let bubble:BubbleEffectEnum
        
        if BINP.check_goddess(accid: accid){
            
            bubble = message.direction == .receive ? .goddessLeftBubble : .goddessRightBubble
            
        }else if let t = BINP.fetch_noble_effect(accid: accid){
            bubble = .nobleBubble(value: t)
        }else{
            bubble = message.direction == .receive ? .normalLeftBubble : .normalRightBubble
        }
        
        
        if bubble == lastBubble{return}
        
        lastBubble = bubble
        
        switch bubble {
        case .normalLeftBubble,.normalRightBubble:
            
            let textColor = message.direction == .send ? rightTextColor:leftTextColor

            chatTextLabel.textColor = textColor
            gradientBackView.alpha = 1
            gradientBackView.borderColor = .clear
            nobleIconImageView.alpha = 0
            goddessBubbleBackView.alpha = 0
            
            if message.direction == .receive{
                gradientBackView.bgLayer.colors = [0xF5F8FA,0xF5F8FA].map{ UIColor(hex: $0) }.compactMap{ $0 }.map({$0.cgColor})
            }else{
                gradientBackView.bgLayer.colors = [0xFEC207,0xFEC207].map{ UIColor(hex: $0) }.compactMap{ $0 }.map({$0.cgColor})
            }
        case .nobleBubble(let t):
            
            chatTextLabel.textColor = rightTextColor

            gradientBackView.borderColor = UIColor(hex: t.colors.borderHexColor)
            gradientBackView.bgLayer.colors = t.colors.gradientHexColors.map{ UIColor(hex: $0) }.compactMap{ $0 }.map({$0.cgColor})
            nobleIconImageView.pin_setImage(from: t.nobleIcon.url)
            nobleIconImageView.alpha = 1
            gradientBackView.alpha = 1
            goddessBubbleBackView.alpha = 0
            
        case .goddessLeftBubble,.goddessRightBubble:
            
            chatTextLabel.textColor = goddessTextColor
            
            goddessBubbleBackView.image = message.direction == .send ? ST_ImageUtils.imageName("goddess_right_bubble") : ST_ImageUtils.imageName("goddess_left_bubble")
            
            nobleIconImageView.alpha = 0
            gradientBackView.alpha = 0
            goddessBubbleBackView.alpha = 1
        }
        
    }
    
    
}






//MARK: - LeftCell
class DTChatTextLeftCell: ST_DTChatTextCell {
    
    override func commonInit() {
        
        super.commonInit()
        
        icon.snp.makeConstraints { (make) in
            make.width.height.equalTo(40)
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(15)
        }
        
        
        gradientBackView.snp.makeConstraints { (make) in
            make.left.equalTo(icon.snp.right).offset(15)
            make.top.equalTo(icon)
            make.width.equalTo(30)
            make.height.equalTo(30)
        }
        
        goddessBubbleBackView.snp.makeConstraints { make in
            make.left.bottom.equalTo(gradientBackView)
            make.top.equalTo(gradientBackView).offset(-14)
            make.right.equalTo(gradientBackView).offset(5)
        }
        
        chatTextLabel.snp.makeConstraints { (make) in
            make.edges.equalTo(gradientBackView).inset(UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10))
        }
        
        self.contentView.addSubview(tailView)
        tailView.snp.makeConstraints { (make) in
            make.height.equalTo(17)
            make.top.equalTo(gradientBackView.snp.bottom).offset(5)
            make.left.equalTo(gradientBackView)
        }
        
        
        
        
        nobleIconImageView.snp.makeConstraints { make in
            make.left.equalTo(gradientBackView).offset(10)
            make.centerY.equalTo(gradientBackView.snp.top)
            make.width.equalTo(28)
            make.height.equalTo(28)
        }
    }
    
    fileprivate lazy var tailView:ST_ChatMessageTailControl = {
         let control = ST_ChatMessageTailControl()
          return control
      }()
    
    override var message: ST_DTChatMessage!{
        didSet{
         
            tailView.model = self.message.tail
            
        }
    }
    
}



//MARK: - RightCell
class DTChatTextRightCell: ST_DTChatTextCell {
    
    override func commonInit() {
        
        super.commonInit()
        
        icon.removeFromSuperview()
        
        gradientBackView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-30)
            make.top.equalToSuperview().offset(15)
            make.width.equalTo(30)
            make.height.equalTo(30)
        }
        
        goddessBubbleBackView.snp.makeConstraints { make in
            make.right.bottom.equalTo(gradientBackView)
            make.top.equalTo(gradientBackView).offset(-14)
            make.left.equalTo(gradientBackView).offset(-10)
        }
        
        chatTextLabel.snp.makeConstraints { (make) in
            make.edges.equalTo(gradientBackView).inset(UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10))
        }
        
        
        contentView.addSubview(upload_error_btn)
        upload_error_btn.snp.makeConstraints { (make) in
            make.right.equalTo(gradientBackView.snp.left).offset(-10)
            make.centerY.equalTo(gradientBackView)
            make.width.height.equalTo(ST_DTChatCell.uploadErrorBtnSize)
        }
        
        
        
        contentView.addSubview(uploadIndicator)
        uploadIndicator.snp.makeConstraints { (make) in
            make.centerY.equalTo(gradientBackView)
            make.right.equalTo(gradientBackView.snp.left).offset(-8)
        }
        
        
        nobleIconImageView.snp.makeConstraints { make in
            make.right.equalTo(gradientBackView).offset(-10)
            make.centerY.equalTo(gradientBackView.snp.top)
            make.width.equalTo(28)
            make.height.equalTo(28)
        }
    }
    
   
    override func setting_uplaod_status() {
        
        super.setting_uplaod_status()
        
        if message.uploadStatus == .uploading {
            
            uploadIndicator.startAnimating()
            
        }else{
            uploadIndicator.stopAnimating()
        }
        
        upload_error_btn.isHidden = message.uploadStatus != .failure
    }
}

//MARK: - Bubble Effect
private enum BubbleEffectEnum:Equatable{
    
    static func == (lhs: BubbleEffectEnum, rhs: BubbleEffectEnum) -> Bool {
        return lhs.effectId == rhs.effectId
    }
    
    /// 左边默认气泡
    case normalLeftBubble
    /// 右边默认气泡
    case normalRightBubble
    /// 贵族气泡
    case nobleBubble(value:GradientEffectStruct)
    /// 女神左边气泡
    case goddessLeftBubble
    /// 女神右边气泡
    case goddessRightBubble
    
    
    var effectId:String?{
        switch self {
        case .normalLeftBubble:
            return 1.string
        case .normalRightBubble:
            return 2.string
        case .nobleBubble(let value):
            return value.nobleIcon
        case .goddessLeftBubble:
            return 3.string
        case .goddessRightBubble:
            return 4.string
        }
    }
}


//MARK:- Gradient Effect
enum NobleEffectEnum:Equatable{
    
    case empty
    case value(v:GradientEffectStruct)
    
    var id:String?{
        switch self {
        case .empty:
            return nil
        case .value(let v):
            return v.nobleIcon
        }
    }
    
    static func == (lhs: NobleEffectEnum, rhs: NobleEffectEnum) -> Bool {
        return lhs.id == rhs.id
    }
}

struct GradientEffectStruct:Codable{
    
    struct GradientEffectColors:Codable {
        let borderHexColor:Int
        let gradientHexColors:[Int]
    }
    
    let colors:GradientEffectColors
    let nobleIcon:String
}

extension GradientEffectStruct{
    
    /// 后台数据库平民🆔 = 14
    static let ORIGINAL_NOBLE_ID = 14
    
    /// 贵族等级 的 颜色
    static let nobleLevelsColor = [GradientEffectColors(borderHexColor: 0xD2C9FF,
                                                        gradientHexColors: [0xE1DBFD,0x9684F2]),
                                   GradientEffectColors(borderHexColor: 0xB4F09E,
                                                        gradientHexColors: [0xC7EFA0,0x95DA67]),
                                   GradientEffectColors(borderHexColor: 0xE4E7FF, gradientHexColors: [0xB4B8CF,0x505977])
                                   ,GradientEffectColors(borderHexColor: 0xC5D4D9, gradientHexColors: [0x9CCFE0,0x416992])
                                   ,GradientEffectColors(borderHexColor:0xFFF29D, gradientHexColors: [0xFEE370,0xBE6801]),GradientEffectColors(borderHexColor: 0xE2DAFE, gradientHexColors: [0xC5A4FE,0x6137C4])
                                   ,GradientEffectColors(borderHexColor: 0x8AF0FE, gradientHexColors: [0x27E1F3,0x3D80EC])
                                   ,GradientEffectColors(borderHexColor: 0xFFC990, gradientHexColors: [0xEB765D,0x9F331B])]
    
    static func effectGenerator(noble:ST_NobleTemporary)->GradientEffectStruct?{
        
        let colorIndex = noble.id - GradientEffectStruct.ORIGINAL_NOBLE_ID - 1
        
        if colorIndex < 0{return nil}
        
        guard let color = GradientEffectStruct.nobleLevelsColor[safe:colorIndex] else {
            return nil
        }
        
        return GradientEffectStruct(colors: color, nobleIcon: noble.url)
        
    }
    
}
